<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <title>Java 后端 WebSocket实现</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
<p>【userId】：
<div><input id="userId" name="userId" type="text" th:value="${userId}"></div>
<p>【toUserId】：
<div><input id="toUserId" name="toUserId" type="text" value=""></div>
<p>【toUserId】：
<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<hr/>
<button onclick="OpenSocket()">开启WebSocket</button>
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript">
    var websocket = null;
    //监听窗口关闭事件
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    function OpenSocket() {
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            var url = "ws://127.0.0.1:8080/websocket/" + $("#userId").val();
            websocket = new WebSocket(url);
        } else {
            alert('当前浏览器 Not support websocket')
        }
        //连接发生错误回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("WebSocket连接发生错误");
        };
        //连接成功建立回调方法
        websocket.onopen = function () {
            setMessageInnerHTML("WebSocket连接成功");
        }
        //接收消息回调方法
        websocket.onmessage = function (event) {
            console.log("我接收："+event.data);
            setMessageInnerHTML(event.data);
        }

        //连接关闭回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("WebSocket连接关闭");
        }
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            var message = document.getElementById('contentText').value;
            console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            websocket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            setMessageInnerHTML(message + "&#13;");
        }
    }
</script>

</html>